package com.lhg.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.lhg.common.CommonResult;
import com.lhg.entity.Info;
import com.lhg.entity.User;
import com.lhg.entity.Vo.InfoVo;
import com.lhg.service.InfoService;
import com.lhg.service.UserService;
import com.lhg.utils.AiRecognizeUtil;
import com.lhg.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/info")
public class InfoController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private InfoService infoService;

    private static final Logger logger = LoggerFactory.getLogger(InfoController.class);
    @PostMapping("/submit")
    public CommonResult<?> submit(@RequestHeader("Authorization") String authHeader,
                                  @RequestBody Info info){
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        info.setUserId(foundUser.getId());
        info.setCreateTime(new java.sql.Date(new java.util.Date().getTime()));
        infoService.insertInfo(info);
        return CommonResult.success("提交成功");

    }

    @PostMapping("/recognize")
    public CommonResult<?> recognize(@RequestBody String content) throws Exception {
        logger.info("ai content data: " + content);
        AiRecognizeUtil aiUtil = new AiRecognizeUtil();
        String questionHeader = "请根据以下邮件内容提取属性信息，邮件内容里不一定有所有信息，但base、size、type、industry这些内容一定可以根据company在互联网上找到，给我返回json形式内容中json的键必须是英文属性名，值是识别或查找到的内容，日期返回格式与‘2024-04-07 19:15:00’一致。（英文属性名：String company; String jobTitle; String website;  String base; String size; String type; String industry; Date examTime; Date interviewTime;分别代表：公司名，岗位名称，笔试或面试链接，公司总部，规模，类型（国企还是私企等），所处行业，笔试开始时间，面试开始时间）";
        String response = aiUtil.vivogpt(content,questionHeader);
        logger.info("Response ai data: " + response);
        Info info = infoService.extractInfo(response);
        logger.info("Response to web data: " + info);
        return CommonResult.success(info);
    }

    @GetMapping("/search")
    public CommonResult<?> search(@RequestHeader("Authorization") String authHeader,
                                  @RequestParam String query,
                                  @RequestParam(defaultValue = "1") Integer currentPage,
                                  @RequestParam(defaultValue = "10") Integer size){
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        PageInfo<Info> page = infoService.selectPage(query, foundUser.getId(), currentPage, size);
        return CommonResult.success(page);
    }

    @DeleteMapping("/delete/batch")
    public CommonResult<?> deleteBatch(@RequestBody List<Integer> ids) {
        infoService.deleteBatch(ids);
        return CommonResult.success("批量删除成功");
    }

    @PostMapping("/edit/{editId}")
    public CommonResult<?> edit(@RequestHeader("Authorization") String authHeader,
                                @PathVariable Integer editId,
                                @RequestBody Info editForm){
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        Info info = infoService.selectById(editId);
        editForm.setCreateTime(info.getCreateTime());
        editForm.setUserId(foundUser.getId());
        editForm.setId(editId);
        infoService.deleteById(editId);
        infoService.insertInfo(editForm);
        return CommonResult.success("编辑成功");
    }

    @GetMapping("/calendar")
    public CommonResult<?> calendarMake(@RequestHeader("Authorization") String authHeader) throws ParseException {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        List<InfoVo> InfoVoList = infoService.calendarMake(foundUser.getId());
        return CommonResult.success(InfoVoList);
    }

    @GetMapping("/searchExam")
    public CommonResult<?> searchExam(@RequestHeader("Authorization") String authHeader,
                                       InfoVo infoVo,
                                       @RequestParam(defaultValue = "1") Integer currentPage,
                                       @RequestParam(defaultValue = "10") Integer size) throws ParseException {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        PageInfo<InfoVo> page = infoService.searchExam(infoVo, foundUser.getId(), currentPage, size);
        return CommonResult.success(page);
    }

    @GetMapping("/suggestion")
    public CommonResult<?> suggest(@RequestHeader("Authorization") String authHeader) throws Exception {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            e.printStackTrace();
            return CommonResult.error(401,"jwt验证出错");
        }
        AiRecognizeUtil aiUtil = new AiRecognizeUtil();
        String questionHeader = "我会分别给你发我今天到期的笔试信息以及未来一周到期的笔试信息，你需要根据我给你的笔试信息，分别从今日建议和未来一周建议两方面，在笔试场次、公司特点、岗位特征以及我的偏好程度方面具体描述，并适当建议。其他要求：如果今日没有笔试，直接表示今日没笔试；如果今日有笔试，给出之前要求的建议；未来一周建议方面其他要求同今日建议。笔试信息如下：";
        InfoVo infoVo = new InfoVo();
        String content = infoService.searchExamContent(infoVo,foundUser.getId());
        String response = aiUtil.vivogpt(content,questionHeader);
        ObjectMapper mapper = new ObjectMapper();
        // 解析外部JSON
        JsonNode rootNode = mapper.readTree(response);
        // 获取data字段中的content字段，并去除转义字符
        String contentString = rootNode.get("data").get("content").asText().replaceAll("\\\\n", "").replaceAll("\\\\\"", "\"");
        logger.info("Response ai data: " + response);
        return CommonResult.success(contentString);
    }

    @GetMapping("/searchInterview")
    public CommonResult<?> searchInterview(@RequestHeader("Authorization") String authHeader,
                                      InfoVo infoVo,
                                      @RequestParam(defaultValue = "1") Integer currentPage,
                                      @RequestParam(defaultValue = "10") Integer size) throws ParseException {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        PageInfo<InfoVo> page = infoService.searchInterview(infoVo, foundUser.getId(), currentPage, size);
        return CommonResult.success(page);
    }

    @GetMapping("/todaySuggestion")
    public CommonResult<?> todaySuggest(@RequestHeader("Authorization") String authHeader) throws Exception {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            e.printStackTrace();
            return CommonResult.error(401,"jwt验证出错");
        }
        AiRecognizeUtil aiUtil = new AiRecognizeUtil();
        String questionHeader = "我会给你发我今天到期的面试信息，你需要根据我给你的面试信息，在面试场次、公司特点、岗位特征、面试轮次以及我的偏好程度方面具体描述，并适当建议。其他要求：如果今日没有面试，直接表示今日没面试；如果今日有面试，给出之前要求的建议。面试信息如下：";
        InfoVo infoVo = new InfoVo();
        String content = infoService.searchTodayInterview(infoVo,foundUser.getId());
        String response = aiUtil.vivogpt(content,questionHeader);
        ObjectMapper mapper = new ObjectMapper();
        // 解析外部JSON
        JsonNode rootNode = mapper.readTree(response);
        // 获取data字段中的content字段，并去除转义字符
        String contentString = rootNode.get("data").get("content").asText().replaceAll("\\\\n", "").replaceAll("\\\\\"", "\"");
        logger.info("Response ai data: " + response);
        return CommonResult.success(contentString);
    }

    @GetMapping("/upcomingSuggestion")
    public CommonResult<?> upcomingSuggest(@RequestHeader("Authorization") String authHeader) throws Exception {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            e.printStackTrace();
            return CommonResult.error(401,"jwt验证出错");
        }
        AiRecognizeUtil aiUtil = new AiRecognizeUtil();
        String questionHeader = "我会给你发我未来一周到期的面试信息，你需要根据我给你的面试信息，在笔试场次、公司特点、岗位特征、面试轮次以及我的偏好程度方面具体描述，并适当建议。其他要求：如果未来一周没有面试，直接表示未来一周没面试；如果未来一周有面试，给出之前要求的建议。面试信息如下：";
        InfoVo infoVo = new InfoVo();
        String content = infoService.searchUpcomingInterview(infoVo,foundUser.getId());
        String response = aiUtil.vivogpt(content,questionHeader);
        ObjectMapper mapper = new ObjectMapper();
        // 解析外部JSON
        JsonNode rootNode = mapper.readTree(response);
        // 获取data字段中的content字段，并去除转义字符
        String contentString = rootNode.get("data").get("content").asText().replaceAll("\\\\n", "").replaceAll("\\\\\"", "\"");
        logger.info("Response ai data: " + response);
        return CommonResult.success(contentString);
    }
}
